#include <msp430.h>
#include <stdint.h>
#include "common.h"
#include "Epaper0213.h"
#include "iic.h"
#include "hdc1080.h"

volatile static uint32_t Timestamp;

void softSPI(uint8 sdbyte)
{
    volatile unsigned int i;
    for (i = 0; i < 8; i++)
    {
        P3OUT &= ~BIT0;
        if (sdbyte & 0x80)
        {

            P3OUT |= BIT4;
        }
        else
        {
            P3OUT &= ~BIT4;
        }
        sdbyte <<= 1;
        P3OUT |= BIT0;
    }
    P3OUT &= ~BIT0;
}

/**
 * main.c
 */
int main(void)
{
    WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer
    BCSCTL1 = CALBC1_1MHZ;    // Set range
    DCOCTL = CALDCO_1MHZ;
    P4SEL = 0;
    P3SEL = 0;
    P2SEL = BIT6 | BIT7;
    P1SEL = 0;
    P1DIR = 0;
    P2DIR = 0;
    P3DIR = 0;
    P4DIR = 0;
    // 休眠 CC110L 和flash
    P4DIR |= BIT6;
    P4OUT |= BIT6;
    P3DIR |= (BIT4 | BIT0 | BIT2);
    P3OUT &= ~BIT2;
    while (P3IN & BIT5)
        ;
    softSPI(0x39);
    while (P3IN & BIT5)
        ;
    delay_ms(10);
    P3OUT |= BIT2;
    P4OUT &= ~BIT6;
    softSPI(0xB9);
    P4OUT |= BIT6;
    P3OUT &= ~BIT4;
    // *********************
    // LED 初始化
    P4SEL &= ~(BIT4 | BIT3 | BIT5);
    P4DIR |= (BIT4 | BIT3 | BIT5);
    P4OUT |= (BIT4 | BIT3 | BIT5);
    // *********************
    // EPD 初始化
    P1DIR &= ~BIT2;
    //    P1REN |=BIT2;
    //    P1OUT|=BIT2;
    P1DIR |= (BIT4 | BIT3);
    P1OUT &= ~BIT4;
    P2DIR |= (BIT5 | BIT1);
    P3DIR |= (BIT1 | BIT3);
    // *********************

    _no_operation();
    //	EPD_BS_L;

    TACCR0 = 32768 - 1;
    TACTL = TASSEL_1 + MC_1; // ACLK, upmode
    TACCTL0 |= CCIE;         // enable TA0CCRO interrupt
    __bis_SR_register(GIE);
    P4DIR |= BIT7;
    P4OUT |= BIT7;
    P3DIR |= BIT6;
    P3OUT |= BIT7;
    I2C_INIT();
    ADC10CTL1 = INCH_11;
    ADC10CTL0 = SREF_1 + ADC10SHT_3 + ADC10SR + REFON + ADC10ON + ENC;
    P4OUT ^= BIT4;
    delay_ms(500);
    P4OUT |= BIT4;
    P4OUT ^= BIT5;
    delay_ms(500);
    P4OUT |= BIT5;
    P4OUT ^= BIT3;
    delay_ms(500);
    P4OUT |= BIT3;
    //检测温湿度类型
    epd_RHtest();
    while (1)
    {
        epd_show();
        __bis_SR_register(LPM3_bits | GIE);
    }

    return 0;
}

// Timer A0 interrupt service routine
#pragma vector = TIMERA0_VECTOR
__interrupt void Timer_A(void)
{
    Timestamp++;
    //    P4OUT^= BIT3;
    if (Timestamp % 15 == 0)
    {
        __bic_SR_register_on_exit(LPM3_bits);
    }
}
